/*
 * Shell.cpp
 *
 *  Created on: Apr 12, 2012
 *      Author: sony
 */

#include "Shell.h"
#include "Token.h"
#include "signal.h"

Shell::Shell() {
	parser = new Parser();
	line = new list<Token*>();

	runApp = true;
}

Shell::~Shell() {
	line->erase(line->begin(), line->end());
	delete parser;
	delete line;
}

void Shell::execute(void) {
	while (runApp) {
		cout << "Shell$ ";
		parseTokens();
		if(runApp) //Omdat runApp intussen (bij de END, ^D) veranderd

			if(!parser->parse(line)){
				parser = new Parser(); //als de parser fout gaat, faalt de verdere afhandeling, daarom nieuwe instantie.
			}
		line->clear();
	}
}
void Shell::leave(int sig) {
	exit(sig);
}
void Shell::parseTokens() {
	Token* token;
	bool stopParsing = false;
	while (!stopParsing) {
		token = nextToken(cin);
		switch (token->getType()) {
		case Token::END:
			stopParsing = true;
			runApp = false;
			break;
		case Token::EOL:
			line->push_back(token);
			stopParsing = true;
			break;
		case Token::SEQUENCE:
			line->push_back(token);
			break;
		case Token::PIPE:
			pipe = true;
			line->push_back(token);
			break;
		case Token::INPUT:
			line->push_back(token);
			break;
		case Token::OUTPUT:
			line->push_back(token);
			break;
		case Token::APPEND:
			line->push_back(token);
			break;
		case Token::WORD:
			if (token->getText() == "exit" || token->getText() == "logout") {
				stopParsing = true;
				runApp = false;
				for (list<Token*>::iterator it = line->begin();
						it != line->end(); it++) {
					delete (*it);
				}
				line->clear();
			}
			line->push_back(token);
			break;
		}
	}
}
